<?php
/**
 * Created by PhpStorm.
 * User: Mars.Li
 * Date: 2015/10/5
 * Time: 14:26
 */
namespace Admin\Controller;

class LinkController extends CommonController {

    public function insert() {

        $model = D (CONTROLLER_NAME);

        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }

        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
            if (!empty($_FILES['icon']['name'])) {
                //上传新头像
                $data['icon'] =  $this->uploadImage(getLinkPath());
                D (CONTROLLER_NAME)->where('id='.$list)->save($data);
            }
            $this->success ('新增成功!');
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
    }

    /**
     * ajax 获取编辑页面数据
     */
    public function edit() {

        $model = D ( CONTROLLER_NAME );
        $id = $_REQUEST [$model->getPk ()];
        $vo = $model->getById ( $id );
        echo json_encode($vo);
    }

   public function update() {

        $model = D ( CONTROLLER_NAME );
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }

        if (!empty($_FILES['icon']['name'])) {
            //上传新头像
            $model->icon =  $this->uploadImage(getLinkPath());
            //删除以前的头像
            $oldfile = $_SERVER['DOCUMENT_ROOT'].D( CONTROLLER_NAME )->where('id='.$model->id)->getField('icon');
            if( file_exists($oldfile) && is_file( $oldfile ) )
            {
                unlink( $oldfile );
            }
        }

        // 更新数据
        $list=$model->save ();

        if (false !== $list) {
            //成功提示
            $this->success('编辑成功!');
        } else {
            //错误提示
            $this->error ('编辑失败!');
        }

    }

    /**
     * 常用链接页面
     */
    public function link() {
        $data = M(CONTROLLER_NAME)->cache(false)->field('title,url,icon,category_id,id')->order('link_order')->select();
        $favoriteLink = M('favorite')->cache(false)->where('user_id='.$_SESSION[C('USER_AUTH_KEY')])->field('id,title,favorite_url,category_id')->select();
        $linklist = array();
        $favoriteList = array();
        $login_key = getUserName();
        foreach ($data as $key => $item) {
            $linklist[$item['category_id']][] = array(
                'title' => $item['title'],
                'url'=> $item['url'],
                'icon'=> $item['icon'],
                'id'=> $item['id'],
            );
        }
        foreach ($favoriteLink as $val){
           $favoriteList[$val['category_id']][] = array(
                'id'            => $val['id'],
                'title'         => $val['title'],
                'favorite_url'  => $val['favorite_url'],
                'category_id'   => $val['category_id'],
            );
        }
        $api = D('api')->cache(true)->where('status=1')->select();
        foreach ($api as $key => $val) {
            switch ($val['platform']) {
                case 0:
                    Vendor('C6.C6Api');
                    $c6 = new \C6Api($val['api_address']);
                    $c6_url = $c6->getLoginUrl();
                    $this->assign('c6_url',$c6_url);
                    break;
                case 1:
                    Vendor('Forum.ForumApi');
                    $forum = new \ForumApi($val['api_address']);
                    $forum_url = $forum->getLoginUrl();
                    $this->assign('forum_url',$forum_url);
                    break;
            }
        }

        $this->assign('link_role',getSiginRoleName());

        $this->assign('ets_login_url',getEtsLoginUrl($login_key));
        $this->assign('linklist',$linklist);
        $this->assign('favoriteList',$favoriteList);
        $this->assign('login_code',getUserName('','user_id'));
        $this->display();
    }

    /**
     * ajax修改链接
     */
    public function ajaxChangeLink() {
        $pk = $_REQUEST['pk'];
        $model = D(CONTROLLER_NAME);
        $data['title'] = $_REQUEST['value']['title'];
        $temp = explode('//',$_REQUEST['value']['link']);
        $data['url'] = $temp[0] == 'http:'?$_REQUEST['value']['link']:'http://'.$_REQUEST['value']['link'];
       // $data['url'] = $_REQUEST['value']['link'];
        if ($pk){
            if ($model->where('id='.$pk)->save($data) === false){
                $this->error('修改失败','',true);
            }
        }else {
            $data['category_id']= $_REQUEST['category_id'];
            if ($model->add($data) === false){
                $this->error('添加失败','',true);
            }
        }
        $this->success('保存成功！','',true);
    }

    /**
     * 删除链接
     */
    public function removeLink(){

        if ($_REQUEST['id']){
            $model = D(CONTROLLER_NAME);
            if ($model->where('id='.$_REQUEST['id'])->delete() === false){
                $this->error('删除失败','',true);
            }
        }else {
            $this->error('删除失败','',true);
        }
        $this->success('删除成功！','',true);
    }

    /**
     * 删除收藏链接
     */
    public function removeFavoriteLink(){
    
        if ($_REQUEST['id']){
            $model = D('favorite');
            if ($model->where('id='.$_REQUEST['id'])->delete() === false){
                $this->error('删除失败','',true);
            }
        }else {
            $this->error('删除失败','',true);
        }
        $this->success('删除成功！','',true);
    }

    /**
     *  链接顶置首页
     */
    public function renderhome(){
        $id = $_REQUEST['id'];
        $tag  = $_REQUEST['tag'];
        $favoriteModel = D('favorite');
        $model = D(CONTROLLER_NAME);
        $data = array();
        $data['header_tag'] = 1;
        if($tag == 'link'){
            $modeldata = $model->getById($id);
            $data['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
            $data['title'] = $modeldata['title'];
            $data['favorite_url'] = $modeldata['url'];
            $data['category_id'] = 8;
            if ($favoriteModel->add($data) === false){
                $this->error('修改失败','',true);
            }
        } else {
            if ($favoriteModel->where('id='.$id)->save($data) === false){
                $this->error('修改失败','',true);
            }
        }
        $this->success('保存成功！','',true);
    }
    
    /**
     * 收藏URL
     */
    public function saveFavorite(){
        $pk = $_REQUEST['pk'];
        $model = D('favorite');
        $data = array();
        $data['user_id']	    =  $_SESSION[C('USER_AUTH_KEY')];
        $data['title']          =  $_REQUEST['value']['title'];
        $data['favorite_url']   =  $_REQUEST['value']['link'];
        $temp = explode('//',$_REQUEST['value']['link']);
        if ($temp[0] != 'http' || $temp[0] != 'https')
            $data['favorite_url']   =  'http://'.$_REQUEST['value']['link'];

        $data['category_id']    = '8';
        if ($pk){
            if ($model->where('id='.$pk)->save($data) === false){
                $this->error('修改失败','',true);
            }
        } else {
                $flag = $model->save($data);
                if ($model->add($data) === false){
                    $this->error('添加失败','',true);
                }
        }
        $this->success('保存成功！','',true);
    }
}